# -*- encoding: utf-8 -*-
from django.db import models
from multilingual.translation import TranslationModel
from django.utils.translation import ugettext_lazy as _

from modulo.page.models import Section

class Gallery(models.Model):
    section = models.ForeignKey(Section, related_name="galleries",
                                limit_choices_to = {'app': 'gallery'},
                                help_text=_(u"Selection de la rubrique contenant cette galerie."))

    slug    = models.CharField(_(u'Répertoire'), help_text=_(u'Répertoire contenant la galerie'), max_length=100)

    order = models.IntegerField(editable=False, default=0)
    
    def save(self):
        if self.order == 0:
            self.order = Gallery.objects.filter(section=self.section).count()+1
        super(Gallery, self).save()

    def get_images(self):
        images = getattr(self, 'images', None)
        if images is None:
            from utils import get_images
            self.images = get_images(self.slug)
        return self.images

    def get_random_image(self):
        images = self.get_images()
        nb_images = len(images)

        if nb_images != 0:
            import random
            r = random.randint(0, nb_images-1)
            return images[r]
        else:
            return None

    def count(self):
        return len(self.get_images())

    def get_absolute_url(self):
        return u'%s%d/' % (self.section.get_absolute_url(), self.id)
        
    def __unicode__(self):
        return u"%s : %s" % (self.slug, self.section)


    class Meta:
        verbose_name = _("galerie")
